﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Json;
using System.IO;

namespace GeoRef
{
    /// <summary>
    /// Provides utility functions to convert any object into JSON
    /// and viceversa
    /// </summary>
    public class GeoSerializer
    {
        /// <summary>
        /// Converts a generic object into its JSON representation
        /// </summary>
        /// <param name="t">The type of the object to be converted</param>
        /// <param name="o">The object to be converted</param>
        /// <example>
        /// <code>
        /// string result = GeoSerializer.ToJsonString(typeof(GeoLoc), new GeoLoc("43.786410, 11.265180", "Largo Adone Zoli, Pisa", "Partenza"));
        /// </code>
        /// </example> 
        /// <returns>A JSON compliant string representing the object</returns>
        public static string ToJsonString(Type t, object o)
        {
            MemoryStream stream = new MemoryStream();
            DataContractJsonSerializer jserializer = new DataContractJsonSerializer(t);
            jserializer.WriteObject(stream, o);
            stream.Position = 0;
            StreamReader sr = new StreamReader(stream);
            return sr.ReadToEnd();
        }

        /// <summary>
        /// Converts a string representing an object in JSON notation
        /// into a C# object
        /// </summary>
        /// <example>
        /// <code>
        /// GeoPoint p = (GeoPoint)FromJsonString(typeof(GeoPoint), "{\"lat\":43.78641,\"lng\":11.26518}");
        /// </code>
        /// </example> 
        /// <param name="t">The type of the object into which the string will be converted</param>
        /// <param name="s">The string to be convertes</param>
        /// <returns>An object of the exact type as requested</returns>
        public static object FromJsonString(Type t, string s)
        {
            MemoryStream stream = new MemoryStream();
            StreamWriter sw = new StreamWriter(stream);
            sw.Write(s);
            sw.Flush();
            stream.Position = 0;
            DataContractJsonSerializer ser = new DataContractJsonSerializer(t);
            return ser.ReadObject(stream);
        }
    }
}
